(function() {

    var URL = {
        // checkMobileUrl: "/wx/loginAccount/checkMobile", //绑定手机号
    };

    //变量池
    var variablePool = { //变量池
        picWidth: 30, //图标宽度
        picRealWidth: 60, //图标实际宽度
        picHeight: 30, //图标高度
        picRealHeight: 60, //图标实际高度
        iconPath: "",
        movePic: "image/diy/move.png",
        rotatePic: "image/diy/rotate.png",
        scalePic: "image/diy/scale.png",
        removePic: "image/diy/remove.png",
        mouseStatus: false,
        viewbox_ratio:1,
    };
    var team777Common = {
        //是否为debug模式
        debug: true,
        //链接地址池
        URL: URL,
        //变量池
        variablePool: variablePool,
        log: function(msg, type) {
            if (console) {
                if(Object.prototype.toString.call((msg)) != '[object Array]') {
                    msg=[msg];
                }
                switch (type) {
                    case "debug":
                        team777Common.debug && console.debug.apply(console,msg);
                        break;
                    case "info":
                        team777Common.debug && console.info.apply(console,msg);
                        break;
                    case "error":
                        console.error.apply(console,msg);
                        break;
                    case "warn":
                        team777Common.debug && console.warn.apply(console,msg);
                        break;
                    case "log":
                    default:
                        team777Common.debug && console.log.apply(console,msg);
                        break;
                }
            }
        },
        convertImgToBase64: function(url, callback, outputFormat) {
            var that = this;
            if (!variablePool[url]) {
                variablePool[url] = 0;
            }
            variablePool[url]++;
            if (url && url.indexOf("data:image/") < 0) { //如果图片为链接地址则转为base64
                url = that.loadImgUrl("", url);
                var canvas = document.createElement('canvas'),
                    ctx = canvas.getContext('2d'),
                    img = new Image;
                img.crossOrigin = 'anonymous';
                img.onload = function() {
                    variablePool[url] = 0;
                    canvas.height = this.height;
                    canvas.width = this.width;
                    ctx.drawImage(img, 0, 0);
                    var dataURL = canvas.toDataURL(outputFormat || 'image/png');
                    // var imageTemp = document.getElementById("model3d_temp_img");
                    // imageTemp.src=dataURL;
                    callback.call(this, dataURL, img.width, img.height);
                    canvas = null;
                    ctx = null;
                    img = null;
                };
                img.onerror = function() {
                    team777Common.log("当前url地址：" + url + "加载失败！", "error");
                    if (that.loadCount < 4) {
                        team777Common.convertImgToBase64(url, callback, outputFormat);
                        // pushSaveLogInfo({ originalPath: url });
                    } else {
                        variablePool[url] = 0;
                        callback.call(this, "");
                    }
                };
                img.src = url;
            } else { //如果图片为为base64  则直接输出
                callback.call(this, url);
            }
        },
        transformPoint: function(x, y, m) {
            return { x: m.a * x + m.c * y + m.e, y: m.b * x + m.d * y + m.f };
        },
        transformBox: function(l, t, w, h, m) {
            var topleft = { x: l, y: t },
                topright = { x: (l + w), y: t },
                botright = { x: (l + w), y: (t + h) },
                botleft = { x: l, y: (t + h) };
            var transformPoint = team777Common.transformPoint;
            topleft = transformPoint(topleft.x, topleft.y, m);
            var minx = topleft.x,
                maxx = topleft.x,
                miny = topleft.y,
                maxy = topleft.y;
            topright = transformPoint(topright.x, topright.y, m);
            minx = Math.min(minx, topright.x);
            maxx = Math.max(maxx, topright.x);
            miny = Math.min(miny, topright.y);
            maxy = Math.max(maxy, topright.y);
            botleft = transformPoint(botleft.x, botleft.y, m);
            minyinx = Math.min(minx, botleft.x);
            maxx = Math.max(maxx, botleft.x);
            miny = Math.min(miny, botleft.y);
            maxy = Math.max(maxy, botleft.y);
            botright = transformPoint(botright.x, botright.y, m);
            minx = Math.min(minx, botright.x);
            maxx = Math.max(maxx, botright.x);
            miny = Math.min(miny, botright.y);
            maxy = Math.max(maxy, botright.y);
            var center = { x: (topleft.x + botright.x) / 2, y: (topleft.y + botright.y) / 2 },
                r = Math.sqrt(Math.pow(topleft.x - botright.x, 2) + Math.pow(topleft.y - botright.y, 2)) / 2;
            return {
                tl: topleft,
                tr: topright,
                bl: botleft,
                br: botright,
                r: r,
                center: center,
                aabox: { x: minx, y: miny, width: (maxx - minx), height: (maxy - miny) }
            };
        },
        //获取鼠标坐标
        getMousePosition: function(e, offset) {
            if (!offset.ratio) {
                offset.ratio = 1;
            }
            var x = e.clientX || e.pageX;
            var y = e.clientY || e.pageY;
            return { x: (x - offset.x) / offset.ratio, y: (y - offset.y) / offset.ratio };
        },
        isDragging: function(e) {
            var changed = e.changedTouches.length,
                touching = e.touches.length;
            return changed === 1 && touching === 1;
        },
        isPinching: function(e) {
            var changed = e.changedTouches.length,
                touching = e.touches.length;
            return (changed === 1 || changed === 2) && touching === 2;
        },
        getTouchedPosition: function(e, offset) {
            if (!offset) {
                offset = { x: 0, y: 0, ratio: 1 };
            }
            var length = e.touches.length;
            switch (length) {
                case 1:
                    return { point1: { x: (e.touches[0].pageX - offset.x) / offset.ratio, y: (e.touches[0].pageY - offset.y) / offset.ratio }, length: length };
                case 2:
                    // m[0].set(e.touches[0].pageX, e.touches[0].pageY, 0);
                    // m[1].set(e.touches[1].pageX, e.touches[1].pageY, 0);
                    return {
                        point1: { x: (e.touches[0].pageX - offset.x) / offset.ratio, y: (e.touches[0].pageY - offset.y) / offset.ratio },
                        point2: { x: (e.touches[1].pageX - offset.x) / offset.ratio, y: (e.touches[1].pageY - offset.y) / offset.ratio },
                        length: length
                    };
                default:
                    return { point1: { x: (e.changedTouches[0].pageX - offset.x) / offset.ratio, y: (e.changedTouches[0].pageY - offset.y) / offset.ratio }, length: length };
            }
        },
        getAngles: function(pos) {
            var touch1 = pos.point1,
                touch2 = pos.point2;
            var angle = 0;
            var ratio=variablePool.viewbox_ratio
            ratio=1;
            if (touch2) {
                var x = (touch1.x - (touch2 ? touch2.x : 0))*ratio,
                    y = (touch1.y - (touch2 ? touch2.y : 0))*ratio;
                angle = Math.atan2(y, x) * 180 / Math.PI;
            }
            return angle;
        },
        getZooms: function(touch) {
            var touch1 = touch.point1,
                touch2 = touch.point2;
                var ratio=variablePool.viewbox_ratio
                ratio=1;
            var x = (touch1.x - (touch2 ? touch2.x : 0))*ratio,
                y = (touch1.y - (touch2 ? touch2.y : 0))*ratio;
            return Math.sqrt((x * x) + (y * y));
        },
        each: function(item, callback) {
            // var len=this.length;
            for (var i in item) {
                if (callback) {
                    callback(item[i], i);
                }
            }
        },
        createCanvas:function(){
            var canvas = document.createElement("canvas");
            if (!window.devicePixelRatio)
                window.devicePixelRatio = 1;
            canvas.width = (document.documentElement.clientWidth || canvas.width) * window.devicePixelRatio;
            canvas.height = (document.documentElement.clientHeight || canvas.height) * window.devicePixelRatio;
            return canvas;
        },
        prototypeDefine: function() {
            //为svg对象设置数组原型方法
            $.extend(Array.prototype, {
                hide: function(callback) {
                    var len = this.length;
                    for (var i = 0; i < len; i++) {
                        if (callback) {
                            callback(this[i], i);
                        } else {
                            this[i].hide();
                        }
                    }
                },
                show: function(callback) {
                    var len = this.length;
                    for (var i = 0; i < len; i++) {
                        if (callback) {
                            callback(this[i], i);
                        } else {
                            this[i].show();
                        }
                    }
                },
                each: function(callback) {
                    var len = this.length;
                    for (var i = 0; i < len; i++) {
                        callback(this[i], i);
                    }
                },
                remove: function(callback) {
                    var len = this.length;
                    for (var i = 0; i < len; i++) {
                        if (callback) {
                            callback(this[i], i);
                        } else {
                            this[i].remove();
                        }
                    }
                }
            });
            $.extend(Object.prototype, {

            });
        },
        loadImgUrl: function(server, imageUrl, last) {
            // var tempath = "";
            // if (imageUrl) {
            //     if ((imageUrl.indexOf("http://") > -1 || imageUrl.indexOf("https://") > -1)) {
            //         // if (imageUrl.indexOf('?') == -1) {
            //         //     tempath = "?" + Math.random(1);
            //         // } else {
            //         //     tempath = "&r=" + Math.random(1);
            //         // }
            //         if (document.location.protocol == "https:") {
            //             imageUrl = imageUrl.replace("http://", "https://");
            //         } else if (document.location.protocol == "http:") {
            //             imageUrl = imageUrl.replace("https://", "http://");
            //         }
            //         imageUrl = imageUrl.replace(".cmall.com/imgsrv//", ".cmall.com/imgsrv/");
            //         //imageUrl= imageUrl;
            //     } else {
            //         //如果有/开头则去掉
            //         if (imageUrl.indexOf("/") == 0) {
            //             imageUrl = imageUrl.substring(1, imageUrl.length);
            //         }
            //         if (last) {
            //             imageUrl = server + imageUrl + last;
            //         } else {
            //             imageUrl = server + imageUrl;
            //         }
            //     }
            //     imageUrl = imageUrl.replace(".cmall.com/imgsrv//", ".cmall.com/imgsrv/");
            // }
            return imageUrl;
        }
    };
    //初始化原型定义
    team777Common.prototypeDefine();
    var vueApp = new Vue({
        el: '#team777Vue',
        data: {
            // isWechat: variablePool.isWechat, //是否为微信客户端
            template: {},
            svgObj: {},
            templateList: [],
            //加载状态
            loadingStatus: true,
            //文字编辑相关
            tabs: [
                {
                    text: "内容",
                    active: true
                }, {
                    text: "字体",
                    active: false
                }, {
                    text: "颜色",
                    active: false
                }
            ],
            colors: [],
            fonts: [],
            text: "",
            show: false,
            editTextBox: document.getElementById("edit-text-box"),
        },
        beforeCreate: function() {
            // team777Common.log('beforeCreate 创建前状态===============》');
            //     team777Common.log("%c%s", "color:red", "el     : " + this.$el); //undefined
            //     team777Common.log("%c%s", "color:red", "data   : ", this.$data); //undefined
            //     team777Common.log("%c%s", "color:red", "message: " + this.message)
        },
        created: function() {
            // team777Common.log('created 创建完毕状态===============》');
            //     team777Common.log("%c%s", "color:red", "el     : " + this.$el); //undefined
            //     team777Common.log("%c%s", "color:red", "data   : ", this.$data); //已被初始化
            //     team777Common.log("%c%s", "color:red", "message: " + this.message); //已被初始化
            var that = this;
            that.loadingStatus = true;
            that.getTemplateList({
                id: window.location.href.getQueryJson().id,
                kind: window.location.href.getQueryJson().kind
            }, function(data) {
                that.templateList = data;
                var len = data ? data.length : 0;
                var template = len > 0 ? that.templateList[0] : null;
                // if(template){
                //     template.content='<svg version="1.1" id="svg-container" width="2392px" height="1636px" viewBox="0 0 2392 1635" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve"><g id="svg_canvas"><g id="svg_background"><rect x="0" y="0" fill="transparent" width="2392" height="1635" /><image id="svg_background" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="flower-bg.png" x="0" y="0" width="2392" height="1635" /></g></g><g id="svg_frame"><mask id="svg_frame-mask"><ellipse fill="#ffffff" opacity="1" cx="1178" cy="632.852" rx="284" ry="356" /></mask><g id="svg_frame_face" mask="url(\'#svg_frame-mask\')"><g id="svg_image"><image xlink:href="custom-1.png" x="895" y="250" width="568" height="692"/></g></g></g></svg>';
                // }
                //<?xml version="1.0" encoding="utf-8"?>
                // <!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
                // <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
                that.template = template;
                if(diyPage){
                    for(var i in that.template) {
                        diyPage.template[i] =that.template[i];
                    }
                }
                $(document).ready(function(){
                    that.createSvg(template,function(){
                        that.loadingStatus = false;
                    });
                });
                // team777Common.log(that.templateList);
            });
            that.renderColor();
            that.renderFont();
        },
        beforeMount: function() {
            // team777Common.log('beforeMount 挂载前状态===============》');
            //     team777Common.log("%c%s", "color:red", "el     : " + (this.$el)); //已被初始化
            //     team777Common.log(this.$el);
            //     team777Common.log("%c%s", "color:red", "data   : ", this.$data); //已被初始化
            //     team777Common.log("%c%s", "color:red", "message: " + this.message); //已被初始化
        },
        beforeUpdate: function() {
            // team777Common.log('beforeUpdate 更新前状态===============》');
            // team777Common.log("%c%s", "color:red", "el     : " + this.$el);
            // team777Common.log(this.$el);
            // team777Common.log("%c%s", "color:red", "data   : ", this.$data);
            // team777Common.log("%c%s", "color:red", "message: " + this.message);
        },
        updated: function() {
            // team777Common.log('updated 更新完成状态===============》');
            // team777Common.log("%c%s", "color:red", "el     : " + this.$el);
            // team777Common.log(this.$el);
            // team777Common.log("%c%s", "color:red", "data   : ", this.$data);
            // team777Common.log("%c%s", "color:red", "message: " + this.message);
        },
        beforeDestroy: function() {
            //     team777Common.log('beforeDestroy 销毁前状态===============》');
            //     team777Common.log("%c%s", "color:red", "el     : " + this.$el);
            //     team777Common.log(this.$el);
            //     team777Common.log("%c%s", "color:red", "data   : ", this.$data);
            //     team777Common.log("%c%s", "color:red", "message: " + this.message);
        },
        destroyed: function() {
            //     team777Common.log('destroyed 销毁完成状态===============》');
            //     team777Common.log("%c%s", "color:red", "el     : " + this.$el);
            //     team777Common.log(this.$el);
            //     team777Common.log("%c%s", "color:red", "data   : ", this.$data);
            //     team777Common.log("%c%s", "color:red", "message: " + this.message)
        },
        mounted: function() {
            // team777Common.log('mounted 挂载结束状态===============》');
            // team777Common.log("%c%s", "color:red", "el     : " + this.$el); //已被初始化
            // team777Common.log(this.$el);
            // team777Common.log("%c%s", "color:red", "data   : " , this.$data); //已被初始化
            // team777Common.log("%c%s", "color:red", "message: " + this.message); //已被初始化
            // team777Common.log("------------------");
            var that = this;
            // alert("diy");
            // setTimeout(function() {
            // }, 1000);
            // });
        },
        // watch: {
        //     show: function(value) {
        //         team777Common.log(value);
        //         var _this = this;

        //         if (value) {
        //             this.editTextBox.classList.add("active");

        //             setTimeout(function() {
        //                 _this.editTextBox.classList.add("effect");
        //             }, 50);

        //         } else {
        //             this.editTextBox.classList.remove("effect");

        //             setTimeout(function() {
        //                 _this.editTextBox.classList.remove("active");
        //             }, 400);
        //         }
        //     }
        // },
        methods: {
            //文字编辑相关
            tabChange: function(index) {
                this.tabs.map(function(value, i) {
                    value.active = index === i ? true : false;
                });
            },
            twoBit: function(color) {
                if (color.length === 1) {
                    color += color;
                }

                return color;
            },
            rgbToHex: function(r, g, b) {
                r = this.twoBit(r.toString(16));
                g = this.twoBit(g.toString(16));
                b = this.twoBit(b.toString(16));

                return r + g + b;
            },
            renderColor: function() {
                // 添加一排灰色
                for (var i = 0; i < 6; i++) {
                    var r = g = b = i * 51;

                    this.colors.push({
                        color: "rgb("+ r +","+ g +","+ b +")",
                        hex: this.rgbToHex(r, g, b),
                        active: false
                    });
                }

                for (var i = 0; i < 3; i++) {
                    for (var j = 0; j < 6; j++) {
                        for (var k = 0; k < 6; k++) {
                            var r = i * 102;
                            var g = j * 51;
                            var b = k  * 51;

                            this.colors.push({
                                color: "rgb("+ r +","+ g +","+ b +")",
                                hex: this.rgbToHex(r, g, b),
                                active: false
                            });
                        }
                    }
                }

                // 默认选中第一个
                this.colors[0].active = true;
            },

            // 显示字体
            renderFont: function() {
                this.$http.get(STATIC_CONFIG.WWWROOT + "/index/index/fonts?user_id="+CommonJs.cookie.get('user_id')||'1').then(function(res) {
                    var data = res.body.message;
                    team777Common.log(res.body.code);
                    if (res.body.code === 200 && data) {
                        this.fonts = data.map(function(value) {
                            return  {
                                id: value.font_id,
                                name: value.name,
                                img: "/ravimg?src="+value.preview_url,
                                active: false
                            };
                        });
                        this.fonts[0].active = true;
                    }
                });
            },

            // 选择字体、颜色
            change: function(data, index) {
                data.map(function(value, i) {
                    value.active = index === i ? true : false;
                });
            },
            // 提交
            submit: function() {
                var me=this;
                if (this.text.trim() === "") {
                    layer.open({
                        content: '至少输入一个文字',
                        skin: 'msg',
                        time: 2 //2秒后自动关闭
                    });
                    return ;
                }
                var id = this.fonts.filter(function(value) {
                    return value.active;
                })[0].id;

                var colorStr = this.colors.filter(function(value) {
                    return value.active;
                })[0].hex;
                var parms = {
                    user_id: CommonJs.cookie.get('user_id'),
                    id: id,
                    text: this.text,
                    fontSize: 500,
                    colorStr: colorStr,
                    isHorizontal: document.getElementById("horizontal").checked
                };
                var load = layer.open({type: 2, shadeClose: false});
                $.ajax({
                    type: "POST",
                    url: STATIC_CONFIG.WWWROOT + "/index/index/text2image",
                    dataType: 'json',
                    data: parms,
                    success: function (res) {
                        if (res.code === 200) {
                            // me.addImage("/ravimg?src="+ res.message.imageUrl);
                            var imageUrl="/ravimg?src="+ res.message.imageUrl;
                            team777Common.convertImgToBase64(imageUrl, function(base64Img, width, height) {
                                var item={imagebase64:base64Img};
                                item.width=width;
                                item.height=height;
                                me.addSvgTextImages(item,function(){
                                    me.show = false;
                                    me.text = "";
                                    layer.close(load);
                                });
                                team777Common.log("加载成功");
                            });
                            // var image=new Image;
                            // image.crossOrigin = 'anonymous';
                            // image.onload=image.onerror=function(){
                               
                            // }
                            // image.src=item.imageUrl;
                        }else{
                            layer.close(load);
                        }
                    },
                    error:function () {
                        layer.close(load);
                    }
                });
            },
            // // 添加文字图片
            // addImage: function(img) {
            //     var div = $(
            //         "<div class='chartlet-item compose-img active'>"+
            //         "<span class='chartlet-del'><i class='iconfont icon-delete'></i></span>"+
            //         "<img src="+ img +" width='100%'>"+
            //         "</div>"
            //     );

            //     div.data("position", {
            //         x: 0,
            //         y: 0,
            //         rotate: 0,
            //         scale: 1
            //     });

            //     $("#edit-chartlet").children().removeClass("active").end().append(div);

            //     $("body").trigger("update", div);
            // },

            //文字相关end
            closeEditTextDialog:function(e){
                if(e.target.id=="edit-text-box"){
                    this.show=false;
                }
            },
            showEditTextDialog:function(e){
                this.show=true;
            },
            //展示新的svg模板
            showNewTemplate: function(item) {
                var that = this;
                that.loadingStatus = true;
                $("#svg_content_box").html("");
                that.template = item;
                that.setBg(item);
                this.createSvg(that.template,function(){
                    that.loadingStatus = false;
                });
            },
            // 设置背景
            setBg:function (data) {
                if(diyPage.template.kind=="bag" && data.surface) {
                    if(data.surface.Handle) {
                        $("#handle-bg").attr("src", data.surface.Handle.url);
                    }
                    if(data.surface.Body) {
                        $("#body-bg").attr("src", data.surface.Body.url);
                    }
                    if(data.surface.Example) {
                        $(".alt-example .view").attr("src", data.surface.Example.url);
                    }
                }
            },
            //获取模板列表
            getTemplateList: function(options, callback) {
                var that = this;
                $.ajax({
                    type: "GET",
                    url: "/diy/template/list",
                    dataType: 'json',
                    data: options,
                    success: function(data) {
                        team777Common.log(data);
                        // that.templateData = result;
                        var result = null;
                        if (data.code == 200) {
                            result = data.message;
                            diyPage.template.kind=data.kind||0;
                            that.setBg(result[0]);
                        }
                        if (callback) {
                            callback(result);
                        }
                    },
                    error: function() {
                        if (callback) {
                            callback();
                        }
                    }
                });
            },
            uploadUserImages: function($event) {
                var that = this;
                var resultFiles = $event.target.files;
                // team777Common.log(resultFiles);
                var resultFile = resultFiles && resultFiles.length > 0 ? resultFiles[0] : null;
                if (resultFile) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        var urlData = this.result;
                        var image=new Image;
                        that.loadingStatus = true;
                        // window.open(urlData);
                        var canvas = document.createElement('canvas'),
                        ctx = canvas.getContext('2d');
                        image.crossOrigin = 'anonymous';
                        image.onload=image.onerror=function(){
                            var item={};
                            item.height= canvas.height = this.height;
                            item.width=canvas.width = this.width;
                            ctx.drawImage(image, 0, 0);
                            var dataURL = canvas.toDataURL('image/png');
                            item.imagebase64=dataURL;
                            that.addSvgUploadImage(item, function() {
                                that.loadingStatus = false;
                            });
                        };
                        image.src=urlData;
                    };
                    reader.readAsDataURL(resultFile);
                }
            },
            /**
             * 添加用户素材
             * [addSvgUploadImage description]
             * @param {[type]} item [description]  素材对象
             */
            addSvgUploadImage: function(item, callback) {
                var that = this;
                var svgObj = that.svgObj,
                    svg = svgObj.svg,
                    uploadImages_g = svgObj.uploadImages_g;
                var width = item.width,
                    height = item.height;
                var userImageData = {
                    orig_width: width,
                    orig_height: height
                };
                that.loadSvgImageByBase64({
                    params: {
                        width: width,
                        height: height,
                        imagebase64: item.imagebase64,
                        isActive: true
                    },
                    data: userImageData,
                    target: uploadImages_g,
                    callback: function(target) {
                        // target.data("type", "uploadImage");
                        var id = target.attr("id");
                        //重新设置图片高宽
                        target.attr({
                            "width": width,
                            "height": height
                        });
                        var viewbox = svg.viewbox();
                        var x = viewbox.width / 2 - width / 2,
                            y = viewbox.height / 2 - height / 2;
                        var scale = Math.min(viewbox.width / width, viewbox.height / height);
                        var matrix = new SVG.Matrix;
                        matrix = matrix.translate(x, y);
                        // matrix=matrix.scale(scale);
                        target.matrix(matrix);
                        target.scale(scale);
                        that.refreshComponent(target, svgObj.selectGroup);
                        // target.translate(x,y);
                        var transform = target.transform();
                        userImageData.matrix = {
                            "rotate": transform.rotation,
                            "scale": transform.scaleX,
                            "translateX": transform.x,
                            "translateY": transform.y
                        };
                        userImageData.matrixString = new SVG.Matrix(target).toString();
                        // svgObj.userImage = target;
                        designModelMap.uploadImages[id] = userImageData;
                        if (callback) {
                            callback();
                        }
                    }
                });
            },
            /**
             * 添加文字图片
             * [addSvgTextImages description]
             * @param {[type]} item [description]  素材对象
             */
            addSvgTextImages: function(item, callback) {
                var that = this;
                var svgObj = that.svgObj,
                    svg = svgObj.svg,
                    textImages_g = svgObj.textImages_g;
                var width = item.width,
                    height = item.height;
                var userImageData = {
                    orig_width: width,
                    orig_height: height
                };
                that.loadSvgImageByBase64({
                    params: {
                        width: width,
                        height: height,
                        imagebase64: item.imagebase64,
                        imageUrl:item.imageUrl,
                        isActive: true
                    },
                    data: userImageData,
                    target: textImages_g,
                    callback: function(target) {
                        // target.data("type", "uploadImage");
                        var id = target.attr("id");
                        //重新设置图片高宽
                        target.attr({
                            "width": width,
                            "height": height
                        });
                        var viewbox = svg.viewbox();
                        var x = viewbox.width / 2 - width / 2,
                            y = viewbox.height / 2 - height / 2;
                        var scale = Math.min(viewbox.width / width, viewbox.height / height);
                        var matrix = new SVG.Matrix;
                        matrix = matrix.translate(x, y);
                        // matrix=matrix.scale(scale);
                        target.matrix(matrix);
                        target.scale(scale);
                        that.refreshComponent(target, svgObj.selectGroup);
                        // target.translate(x,y);
                        var transform = target.transform();
                        userImageData.matrix = {
                            "rotate": transform.rotation,
                            "scale": transform.scaleX,
                            "translateX": transform.x,
                            "translateY": transform.y
                        };
                        userImageData.matrixString = new SVG.Matrix(target).toString();
                        // svgObj.userImage = target;
                        designModelMap.textImages[id] = userImageData;
                        if (callback) {
                            callback();
                        }
                    }
                });
            },
            saveEditSvg:function () {
                // alert('start');
                var that=this;
                console.log(that);
                var svgObj =that.svgObj;
                var back = designModelMap.back,
                    textImages = designModelMap.textImages,
                    uploadImages = designModelMap.uploadImages,
                    maskImage = designModelMap.mask;

                    var svg = svgObj.svg,
                    canvas_g = svgObj.canvas_g,
                    back_g = svgObj.back_g,
                    face_g = svgObj.face_g,
                    uploadImages_g = svgObj.uploadImages_g,
                    textImages_g = svgObj.textImages_g,
                    mask = svgObj.mask;

                    // svg=SVG.get("svg_canvas");

                    var svgTemp = svg.node.cloneNode(false);
                    // svgTemp.remove();
                    $(svgTemp).removeAttr("x");
                    $(svgTemp).removeAttr("y");
                    $(svgTemp).attr({ xmlns: "http://www.w3.org/2000/svg", "xmlns:xlink": "http://www.w3.org/1999/xlink" });
                    $(svgTemp).attr({ width: variablePool.svg_orig_width, height: variablePool.svg_orig_height });
                    $(svgTemp).html($(canvas_g.node).html());
                    var $svgContent = $("<div></div>").append($(svgTemp));
                    var svgContent = $svgContent.html();
                    svgContent = svgContent.replace(/ns[\d]*:href/ig, "xlink:href");
                    // team777Common.log(svgContent);
                    that.svgRenderCanvas(svgContent, variablePool.svg_orig_width, variablePool.svg_orig_height, function(base64Img) {
                        // alert("渲染成canvas finish!");
                        diyPage.template.origin_price=that.template.origin_price||0;
                        diyPage.upLoadUrl=base64Img;
                        // window.open(base64Img);
                        diyPage.counts();
                        diyPage.openAddOrd(base64Img);
                        // team777Common.log(base64Img);
                        //@TODO  增加上传图片处理  finish
                    });
                // });
            },
            /**
             * [addSvgMask description]  添加蒙版
             * @param {[type]}   item     [description]
             * @param {Function} callback [description]
             */
            addSvgMask: function(item, callback) {
                var that = this;
                var svgObj = that.svgObj,
                    svg = svgObj.svg,
                    mask = svgObj.mask,
                    slitTypeMap = svgObj.slitTypeMap ? svgObj.slitTypeMap : {},
                    face_g = svgObj.face_g;
                var width = item.width,
                    picWidth = slitTypeMap.picWidth,
                    height = item.height,
                    picHeight = slitTypeMap.picHeight,
                    xaxis = slitTypeMap.xaxis || 0,
                    yaxis = slitTypeMap.yaxis || 0,
                    dpi = item.imgDpi || 200,
                    imageUrl = item.url;
                // var originalImageUrl = team777Common.loadImgUrl(team777Common.imgService.imgServer, imageUrl);
                // var thumbilUrl=team777Common.loadImgUrl(team777Common.imgService.imgServer,imageUrl,team777Common.imgService.qnProduct300);
                var dataImgPath = team777Common.loadImgUrl("", imageUrl, team777Common.imgService.qnProductDync.substitute({ width: "", height: "", quality: "/q/30" }));
                var imgPath = team777Common.imgService.imgServer + dataImgPath;
                var maskImageData = {
                    orig_width: width,
                    orig_height: height,
                    remoteImageUrl: imageUrl,
                    remoteOriginalImageUrl: imageUrl
                };
                team777Common.convertImgToBase64(imgPath, function(base64Img, width, height) {
                    maskImageData.imagebase64 = base64Img;
                    maskImageData.orig_width = width;
                    maskImageData.orig_height = height;
                    var ratio = 1;
                    ratio = Math.min(picHeight * ratio / height, picWidth * ratio / width);
                    //重新设置图片高宽
                    width = width * ratio;
                    height = height * ratio;
                    xaxis = picWidth / 2 - width / 2 + xaxis;
                    yaxis = picHeight / 2 - height / 2 + yaxis;
                    var maskImage = svgObj.maskImage;
                    if (!maskImage) {
                        maskImage = svg.image(base64Img, width, height);
                        mask.add(maskImage);
                        face_g.maskWith(mask);
                    } else {
                        maskImage.load(base64Img);
                        maskImage.attr({
                            "width": width,
                            "height": height
                        });
                    }
                    var id = maskImage.attr("id");
                    // var viewbox = svg.viewbox();
                    // if(picWidth<picHeight){//如果区域宽大于高则 宽居中
                    //     xaxis=picWidth/2-width/2+xaxis;
                    // }else{
                    //     yaxis=picHeight/2-height/2+yaxis;
                    // }
                    maskImage.attr({
                        // "width": width,
                        // "height": height,
                        "x": xaxis,
                        "y": yaxis
                    });
                    // var x = viewbox.width / 2 - width / 2+xaxis,
                    //     y = viewbox.height / 2 - height / 2+yaxis;
                    // var x = xaxis,
                    //     y = yaxis;
                    var matrix = new SVG.Matrix;
                    // matrix = matrix.translate(x, y);
                    // maskImage.matrix(matrix);
                    // maskImage.scale(ratio);
                    // refreshComponent(maskImage,svgObj.selectGroup);
                    var transform = maskImage.transform();
                    maskImageData.matrix = {
                        "rotate": transform.rotation,
                        "scale": transform.scaleX,
                        "translateX": transform.x,
                        "translateY": transform.y
                    };
                    maskImageData.matrixString = new SVG.Matrix(maskImage).toString();
                    svgObj.maskImage = maskImage;
                    designModelMap.mask[id] = maskImageData;
                    if (callback) {
                        callback();
                    }
                });
            },
            //将Svg 渲染成canvas
            svgRenderCanvas: function(svg, width, height, callback, outputFormat) {
                var c = team777Common.createCanvas();
                width = width || 512;
                height = height || 512;
                c.width = width;
                c.height = height;
                canvg(c, svg, {
                    log: true,
                    renderCallback: function() {
                        // window.open(c.toDataURL());
                        var dataURL = c.toDataURL(outputFormat || 'image/png', 2.0);
                        if (callback) {
                            callback(dataURL);
                        }
                    }
                });
            },
            loadSvgMaskImageByBase64: function(options) {
                var that = this;
                var svgObj = that.svgObj,
                    svg = svgObj.svg;
                var params = options.params,
                    data = options.data,
                    target = options.target,
                    callback = options.callback,
                    width = params.width,
                    height = params.height;
                if (data.imagebase64) {
                    var temp_image = svg.image(params.imagebase64, width, height);
                    if (data.matrixString || data.matrix) {
                        if (data.matrixString) {
                            temp_image.matrix(data.matrixString);
                        } else {
                            var matrix = new SVG.Matrix;
                            matrix = matrix.translate(data.matrix.translateX, data.matrix.translateY);
                            matrix = matrix.scale(data.matrix.scale, 0, 0);
                            matrix = matrix.rotate(data.matrix.rotate, 0, 0);
                            temp_image.matrix(matrix);
                        }
                    }
                    target.add(temp_image);
                    // if (params.isActive) {
                    //     temp_image.data("name", "image");
                    //     addOperateGroup(temp_image, "hide");
                    // }
                    if (callback) {
                        callback(temp_image);
                    }
                } else {
                    team777Common.convertImgToBase64(params.imageUrl, function(base64Img) {
                        data.imagebase64 = base64Img;
                        var temp_image = svg.image(base64Img, width, height);
                        if (data.matrixString || data.matrix) {
                            if (data.matrixString) {
                                temp_image.matrix(data.matrixString);
                            } else {
                                var matrix = new SVG.Matrix;
                                matrix = matrix.translate(data.matrix.translateX, data.matrix.translateY);
                                matrix = matrix.scale(data.matrix.scale, 0, 0);
                                matrix = matrix.rotate(data.matrix.rotate, 0, 0);
                                temp_image.matrix(matrix);
                            }
                        }
                        target.add(temp_image);
                        // if (params.isActive) {
                        //     temp_image.data("name", "image");
                        //     addOperateGroup(temp_image, "hide");
                        // }
                        if (callback) {
                            callback(temp_image);
                        }
                    });
                }
            },
            // 加载蒙版图片
            loadMaskImage: function(maskImage, callback) {
                var that = this;
                var svgObj = that.svgObj,
                    slitTypeMap = svgObj.slitTypeMap ? svgObj.slitTypeMap : {},
                    mask = svgObj.mask,
                    face_g = svgObj.face_g;
                if (maskImage && maskImage.remoteImageUrl) {
                    var imageUrl = maskImage.remoteImageUrl;
                    var dataImgPath = team777Common.loadImgUrl("", imageUrl);
                    var imgPath = "" + dataImgPath;
                    that.loadSvgMaskImageByBase64({
                        params: {
                            width: maskImage.orig_width,
                            height: maskImage.orig_height,
                            imagebase64: maskImage.imagebase64,
                            imageUrl: imgPath,
                            // isActive: true
                        },
                        data: maskImage,
                        target: mask,
                        callback: function(target) {
                            // target.data("type","uploadImage");
                            var id = target.attr("id");
                            face_g.maskWith(mask);
                            designModelMap.mask[id] = maskImage;
                            svgObj.maskImage = target;
                            if (callback) {
                                callback();
                            }
                        }
                    });
                } else {
                    if (callback) {
                        callback();
                    }
                }
            },
            // 加载背景图片
            loadBackgroundImage: function(backgroundImage, callback) {
                var that = this;
                if (!backgroundImage) {
                    if (callback) {
                        callback();
                    }
                    return;
                }
                var svgObj = that.svgObj,
                    back_g = svgObj.back_g;
                var imageUrl = backgroundImage.remoteImageUrl;
                // var originalImageUrl = team777Common.loadImgUrl("", imageUrl);
                // var thumbilUrl=team777Common.loadImgUrl("",imageUrl,team777Common.imgService.qnProduct300);
                var imgPath = team777Common.loadImgUrl("", imageUrl);
                if (backgroundImage) {
                    that.loadSvgImageByBase64({
                        params: {
                            width: backgroundImage.orig_width,
                            height: backgroundImage.orig_height,
                            imagebase64: backgroundImage.imagebase64,
                            imageUrl: imgPath,
                            // isActive: true
                        },
                        data: backgroundImage,
                        target: back_g,
                        callback: function(target) {
                            target.data("type", "Image");
                            var id = target.attr("id");
                            designModelMap.backgroundImage[id] = backgroundImage;
                            svgObj.backgroundImage = target;
                            if (callback) {
                                callback();
                            }
                        }
                    });
                } else {
                    if (callback) {
                        callback();
                    }
                }
            },

            /**
             * [loadSvgImageByBase64 description]
             * @param  {[type]} options [
             *             params{imagebase64:图片的base64,
             *                     imagerl:图片地址,
             *                     width：图片宽度,
             *                     height:图片高度
             *                     isActive:是否是活动组件                 *
             *                     }
             *             data:传入的需要改变的数据对象
             *             target:创建的图片需要加入到的对象
             *             callback:回调函数
             * ]
             *
             * @return {[type]}         [description]
             */
            loadSvgImageByBase64: function(options) {
                var that = this;
                var svgObj = that.svgObj,
                    svg = svgObj.svg;
                var params = options.params,
                    data = options.data,
                    target = options.target,
                    callback = options.callback,
                    imageObj = options.imageObj,
                    width = params.width,
                    height = params.height,
                    isExsists = false;
                if (params.imagebase64) {
                    var temp_image = imageObj;
                    if (temp_image) {
                        temp_image.load(params.imagebase64);
                        isExsists = true;
                    } else {
                        temp_image = svg.image(params.imagebase64, width, height);
                    }
                    if (data.matrixString || data.matrix) {
                        if (data.matrixString) {
                            temp_image.matrix(data.matrixString);
                        } else {
                            var matrix = new SVG.Matrix;
                            matrix = matrix.translate(data.matrix.translateX, data.matrix.translateY);
                            matrix = matrix.scale(data.matrix.scale, 0, 0);
                            matrix = matrix.rotate(data.matrix.rotate, 0, 0);
                            temp_image.matrix(matrix);
                        }
                    }
                    if (!isExsists) {
                        target.add(temp_image);
                        if (params.isActive) {
                            temp_image.data("name", "image");
                            that.addOperateGroup(temp_image, "hide");
                        }
                    }
                    if (callback) {
                        callback(temp_image);
                    }
                } else {
                    team777Common.convertImgToBase64(params.imageUrl, function(base64Img) {
                        data.imagebase64 = base64Img;
                        var temp_image = imageObj;
                        if (temp_image) {
                            temp_image.load(base64Img);
                            isExsists = true;
                        } else {
                            temp_image = svg.image(base64Img, width, height);
                        }
                        if (data.matrixString || data.matrix) {
                            if (data.matrixString) {
                                temp_image.matrix(data.matrixString);
                            } else {
                                var matrix = new SVG.Matrix;
                                matrix = matrix.translate(data.matrix.translateX, data.matrix.translateY);
                                matrix = matrix.scale(data.matrix.scale, 0, 0);
                                matrix = matrix.rotate(data.matrix.rotate, 0, 0);
                                temp_image.matrix(matrix);
                            }
                        }
                        if (!isExsists) {
                            target.add(temp_image);
                            if (params.isActive) {
                                temp_image.data("name", "image");
                                that.addOperateGroup(temp_image, "hide");
                            }
                        }
                        if (callback) {
                            callback(temp_image);
                        }
                    });
                }
            },
            /**
             * 加载用户上传图片
             */
            loadUploadImages: function(index, uploadImages, callback) {
                var that = this;
                var svgObj = that.svgObj,
                    uploadImages_g = svgObj.uploadImages_g,
                    materLen = uploadImages ? uploadImages.length : 0;
                if (index >= materLen) {
                    if (callback) {
                        callback();
                    }
                    return;
                }
                var obj = uploadImages[index];
                if (!obj) {
                    if (callback) {
                        callback();
                    }
                    return;
                }
                var imageUrl = obj.remoteImageUrl;
                var imgPath = team777Common.loadImgUrl("", imageUrl);
                that.loadSvgImageByBase64({
                    params: {
                        width: obj.orig_width,
                        height: obj.orig_height,
                        imagebase64: obj.imagebase64,
                        imageUrl: imgPath,
                        isActive: true
                    },
                    data: obj,
                    target: uploadImages_g,
                    callback: function(target) {
                        var id = target.attr("id");
                        designModelMap.uploadImages[id] = obj;
                        index++;
                        that.loadUploadImages(index, uploadImages, callback);
                    }
                });
            },
            /**
             * 加载文字图片
             */
            loadTextImages: function(index, textImages, callback) {
                var that = this;
                var svgObj = that.svgObj,
                    textImages_g = svgObj.textImages_g,
                    materLen = textImages ? textImages.length : 0;
                if (index >= materLen) {
                    if (callback) {
                        callback();
                    }
                    return;
                }
                var obj = textImages[index];
                if (!obj) {
                    if (callback) {
                        callback();
                    }
                    return;
                }
                var imageUrl = obj.remoteImageUrl;
                var imgPath = team777Common.loadImgUrl("", imageUrl);
                that.loadSvgImageByBase64({
                    params: {
                        width: obj.orig_width,
                        height: obj.orig_height,
                        imagebase64: obj.imagebase64,
                        imageUrl: imgPath,
                        isActive: true
                    },
                    data: obj,
                    target: textImages_g,
                    callback: function(target) {
                        var id = target.attr("id");
                        designModelMap.textImages[id] = obj;
                        index++;
                        that.loadTextImages(index, textImages, callback);
                    }
                });
            },
            /**
             * 刷新组件
             *
             */
            refreshComponent: function(target, group, textType) {
                // if (!target) {
                //     determinePintInArea();
                // }
                // if(1==1){
                //     return;
                // }
                var _id = target.attr("id"),
                    _name = target.data("name"),
                    _type = target.data("type"),
                    obj = null;
                if (_name == "image") {
                    if (_type == "uploadImage") {
                        obj = designModelMap.userImage;
                    } else {
                        obj = designModelMap.materials;
                    }
                } else if (_name == "text") {
                    obj = designModelMap.texts;
                }
                if (obj) { //重置所有属性  文字图片
                    refreshImageTextProperties(target, obj, _name, textType);
                }
                var transform = target.transform();
                var bbox = target.bbox();
                var l = bbox.x,
                    t = bbox.y,
                    w = bbox.width,
                    h = bbox.height,
                    bbox = { x: l, y: t, width: w, height: h };
                var matrix = new SVG.Matrix(target);
                var transformBox = team777Common.transformBox(l, t, w, h, matrix);
                //判断是否超出可编辑区
                // determinePintInArea(transformBox);
                group.each(function(item) {
                    var name = item.data("name");
                    switch (name) {
                        case "move":
                            item.attr({
                                "x": transformBox.tl.x - variablePool.icon_width/2,
                                "y": transformBox.tl.y - variablePool.icon_width/2
                            });
                            break;
                        case "scale":
                            item.attr({
                                "x": transformBox.tr.x - variablePool.icon_width/2,
                                "y": transformBox.tr.y - variablePool.icon_width/2
                            });
                            break;
                        case "rotate":
                            item.attr({
                                "x": transformBox.br.x - variablePool.icon_width/2,
                                "y": transformBox.br.y - variablePool.icon_width/2
                            });
                            break;
                        case "remove":
                            item.attr({
                                "x": transformBox.bl.x - variablePool.icon_width/2,
                                "y": transformBox.bl.y - variablePool.icon_width/2
                            });
                            break;
                        case "path":
                            item.plot('M ' + transformBox.tl.x + ' ' + transformBox.tl.y + ' L ' + transformBox.tr.x + ' ' + transformBox.tr.y + ' ' + transformBox.br.x + ' ' + transformBox.br.y + ' ' + transformBox.bl.x + ' ' + transformBox.bl.y + ' Z');
                            break;
                        case "circle":
                            item.attr({
                                "cx": transformBox.center.x,
                                "cy": transformBox.center.y,
                                "r": transformBox.r,
                                "stroke": "#000",
                                "fill": "none"
                            });
                            break;
                        default:
                            break;
                    }
                });
            },
            //创建svg图形
            createSvg: function(data,callback) {
                // $(".container .MaindLoadingOver").show();
                var that = this;
                data = $.extend(true, {}, data);
                var svgObj = {};
                that.svgObj = svgObj;
                var svg_container = SVG("svg_content_box");
                svgObj.svg_container = svg_container;
                // var w_width = $(window).width(),
                // w_height = $(window).height();
                var $svg_content_box=$("#svg_content_box");
                var w_width = $svg_content_box.width(),
                w_height = $(window).height();

                 //重置裁片设计的相关数据模型
                 designModelMap = {
                    // back: {}, //基础数据
                    backgroundImage: {}, //背景图片
                    uploadImages: {}, //用户图片
                    textImages: {}, //文字图片
                    mask: {}, //蒙版
                };
                var offset = { x:0, y: 0 };
                // data.editorRegionHeight = 512;
                // data.editorRegionWidth = 512;
                // svg.viewbox({ x: 0, y: 0, width: data.editorRegionWidth, height: data.editorRegionHeight });
                // svg.size(svg_width, svg_height);
                // svg.attr(offset);
                offset.ratio = 1;
                svgObj.offset = offset;
                if(data.content){
                    $(svg_container.node).html(data.content);
                    var svg=SVG.get("svg-container");
                    svgObj.svg = svg;
                    var container_width=variablePool.svg_orig_width=svg.attr("width");
                    var container_height=variablePool.svg_orig_height=svg.attr("height");
                    var ratio=w_width/parseFloat(container_width);
                    var sizeObj={width:w_width,height:parseFloat(container_height)*ratio}
                    sizeObj.y=0;
                    svg.attr(sizeObj);
                    svg_container.attr({width:w_width,height:sizeObj.height});
                    // svg_container.attr({width:w_width,height:w_height});

                    // 画布层
                var canvas_g = SVG.get("svg_canvas");
                svgObj.canvas_g = canvas_g;

                function loadChildren(item){
                    var children=typeof(item.children)=="function"?item.children():[];
                    if(children&&children.length>0){
                        children.each(function(item,index){
                            loadChildren(item)
                        })
                    }else{
                        team777Common.log(item.type);
                        if(item.type=="image"){
                            var url=item.attr("xlink:href");
                            team777Common.convertImgToBase64(url, function(base64Img, width, height) {
                                item.load(base64Img);
                                team777Common.log("加载成功");
                            });
                        }
                    }
                }

                if(canvas_g){
                    canvas_g.children().each(function(item,index){
                        loadChildren(item);
                    })
                }

                //背景层
                var back_g = SVG.get("svg_background");                
                svgObj.back_g = back_g;
                //框架层
                var frame_g = SVG.get("svg_frame");
                svgObj.frame_g = frame_g;
                var mask = SVG.get("svg_frame_mask");
                svgObj.mask = mask;
                var face_g = SVG.get("svg_frame_face");
                svgObj.face_g = face_g;
                var textImages_g = SVG.get("svg_texts");
                    uploadImages_g = SVG.get("svg_images");

                    if(uploadImages_g){
                        uploadImages_g.children().each(function(item,index){
                            item.data("name","image");
                            that.addOperateGroup(item, "hide");
                        });
                    }else{
                        uploadImages_g=face_g.group();
                        uploadImages_g.attr({"id":"svg_images"})
                    }
                    if(textImages_g){
                        textImages_g.children().each(function(item,index){
                            item.data("name","image");
                            that.addOperateGroup(item, "hide");
                        });
                    }else{
                        textImages_g=face_g.group();
                        textImages_g.attr({"id":"svg_texts"})
                    }
                    svgObj.uploadImages_g = uploadImages_g;
                    svgObj.textImages_g = textImages_g;
                    if(callback){
                        callback();
                    }
                    return;
                }


                var svg = svg_container.nested();
                svg.attr({ id: "svg-container" })
                svgObj.svg = svg;
                // function loadSvgContainer(data) {

                var xaxis = 0,
                    yaxis = 0;
                svg_height = 512,
                    svg_width = 512;
                var ratio = 1;
                var see_height = 0;

                svg_width = svg_width * ratio;
                svg_height = svg_height * ratio;
                svg_container.size(w_width, w_height - 100);
                xaxis = xaxis * ratio * 2;
                yaxis = yaxis * ratio * 2;

                // var offset = { x: (w_width - svg_width) / 2, y: (w_height - svg_height) / 2 };
                var offset = { x: (w_width - svg_width - xaxis) / 2, y: 0 };
                data.editorRegionHeight = 512;
                data.editorRegionWidth = 512;
                svg.viewbox({ x: 0, y: 0, width: data.editorRegionWidth, height: data.editorRegionHeight });
                svg.size(svg_width, svg_height);
                svg.attr(offset);
                offset.ratio = 1;
                svgObj.offset = offset;
                // }

                // loadSvgContainer(data);
                //窗口变化重新规划
                // window.dataTemp={editorRegionWidth:data.editorRegionWidth,editorRegionHeight:data.editorRegionHeight};
                // window.onresize=function(){
                //     var dataTemp=window.dataTemp;
                //     loadSvgContainer(dataTemp);
                // };

                // 画布层
                var canvas_g = svg.group();
                svgObj.canvas_g = canvas_g;
                canvas_g.attr({ id: "svg_canvas" });

                //背景层
                // var back_g = svg.group();
                //背景图片层
                var back_g = svg.group();
                //背景图片层
                // var bgcolor_g = svg.group();
                // svgObj.back_g = back_g;
                svgObj.back_g = back_g;
                // svgObj.bgcolor_g = bgcolor_g;
                back_g.attr({ id: "svg_background" });
                // if (data.backgroundImage) {
                //     var backgroundUrl = backgroundImage;
                //     var b_image = svg.image(backgroundUrl, data.orig_width, data.orig_width);
                //     back_g.add(b_image);
                // }
                //框架层
                var frame_g = svg.group();
                svgObj.frame_g = frame_g;
                frame_g.attr({ id: "svg_frame" });
                var mask = svg.mask();
                mask.attr({
                    id: "svg_frame_mask"
                });
                svgObj.mask = mask;
                var face_g = svg.group();
                svgObj.face_g = face_g;
                var textImages_g = svg.group(),
                    uploadImages_g = svg.group();
                uploadImages_g.attr({ id: "svg_images" });
                textImages_g.attr({ id: "svg_texts" });
                face_g.attr({ id: "svg_frame_face" });
                face_g.add(uploadImages_g); //用户图片层
                face_g.add(textImages_g); //文字图片层
                svgObj.uploadImages_g = uploadImages_g;
                svgObj.textImages_g = textImages_g;
                // svgObj.texts_g = texts_g;
                frame_g.add(mask).add(face_g);


                // //装饰层
                // var decorator_g = svg.group();
                // svgObj.decorator_g = decorator_g;
                // decorator_g.attr({
                //     id: "svg_decorator",
                //     "pointer-events": "none"
                // });

                // //添加装饰层图片
                // // var de_image = svg.image(team777Common.loadImgUrl("",data.outLineMaskUrl, team777Common.imgService.qnProductDync.substitute({width:"",height:"", quality: "/q/30" })), data.editorRegionWidth, data.editorRegionHeight);
                // var de_image = svg.image(team777Common.loadImgUrl("", data.outLineMaskUrl), data.editorRegionWidth, data.editorRegionHeight);
                // de_image.style({ "opacity": .5 });
                // decorator_g.add(de_image);

                // var temp = $.extend(true, {}, data);
                // delete temp.textImages;
                // delete temp.texts;
                // delete temp.uploadImages;
                // designModelMap.back = temp;

                var maskImage = data.mask,
                    uploadImages = data.uploadImages,
                    backgroundImage = data.backgroundImage,
                    textImages = data.textImages,
                    materLen = textImages ? textImages.length : 0,
                    texts = data.texts,
                    textLen = texts ? texts.length : 0;
                that.loadBackgroundImage(backgroundImage, function() {
                    that.loadMaskImage(maskImage, function() {
                        var user_image_index = 0;
                        that.loadUploadImages(user_image_index, uploadImages, function() {
                            var text_image_index = 0;
                            that.loadTextImages(text_image_index, textImages, function() {
                                data = null;
                                svgObj = null;
                                if(callback){
                                    callback();
                                }
                            });
                        });
                    });
                });

                canvas_g.add(back_g)
                    .add(frame_g)
                    // .add(decorator_g);
            },
            addOperateGroup: function(target, type) {
                var that = this;
                var svgObj = that.svgObj,
                    selectGroup = svgObj.selectGroup;
                if (selectGroup) {
                    selectGroup.each(function(item) {
                        var name = item.data("name");
                        if (name != "image") {
                            item.hide();
                        }
                    });
                }
                var svg = svgObj.svg,
                    svg_container = svgObj.svg_container,
                    offset = svgObj.offset;
                var bbox = target.bbox();
                var l = bbox.x,
                    t = bbox.y,
                    w = bbox.width,
                    h = bbox.height,
                    bbox = { x: l, y: t, width: w, height: h };
                var matrix = new SVG.Matrix(target);
                var transformBox = team777Common.transformBox(l, t, w, h, matrix);
                //判断是否超出可编辑区
                // determinePintInArea(transformBox);
                var operate_g = svg.group();
                var icon_group = [];
                icon_group.push(target);
                //svg viewbox 处理
                var viewbox = svg.viewbox();
                var ratio_temp=variablePool.viewbox_ratio=viewbox.width/512;
                var path = svg.path('M ' + transformBox.tl.x + ' ' + transformBox.tl.y + ' L ' + transformBox.tr.x + ' ' + transformBox.tr.y + ' ' + transformBox.br.x + ' ' + transformBox.br.y + ' ' + transformBox.bl.x + ' ' + transformBox.bl.y + ' Z');
                path.attr({
                    "stroke": "#000",
                    "fill": "none",
                    "stroke-width": 1*ratio_temp,
                    "stroke-dasharray": 8*ratio_temp+","+ratio_temp*3
                });
                path.data("name", "path");
                icon_group.push(path);

                var circle = svg.circle(transformBox.r * 2);
                circle.center(transformBox.center.x, transformBox.center.y);
                circle.attr({
                    "stroke": "#000",
                    "stroke-width": 1*ratio_temp,
                    "fill": "none"
                });
                circle.hide();
                circle.data("name", "circle");
                icon_group.push(circle);

                var icon_width=variablePool.icon_width=30*ratio_temp;
                var move_image = svg.image(variablePool.iconPath + variablePool.movePic, icon_width, icon_width);
                move_image.attr({
                    "x": transformBox.tl.x - icon_width/2,
                    "y": transformBox.tl.y - icon_width/2
                });
                // team777Common.log("move_image",move_image.attr());
                move_image.data("name", "move");
                icon_group.push(move_image);
                var scale_image = svg.image(variablePool.iconPath + variablePool.scalePic, icon_width, icon_width);
                scale_image.attr({
                    "x": transformBox.tr.x - icon_width/2,
                    "y": transformBox.tr.y - icon_width/2
                });
                // team777Common.log("scale_image",scale_image.attr());
                scale_image.data("name", "scale");
                icon_group.push(scale_image);
                var rotate_image = svg.image(variablePool.iconPath + variablePool.rotatePic, icon_width, icon_width);
                rotate_image.attr({
                    "x": transformBox.br.x - icon_width/2,
                    "y": transformBox.br.y - icon_width/2
                });
                // team777Common.log("rotate_image",rotate_image.attr());
                rotate_image.data("name", "rotate");
                icon_group.push(rotate_image);
                var remove_image = svg.image(variablePool.iconPath + variablePool.removePic, icon_width, icon_width);
                remove_image.attr({
                    "x": transformBox.bl.x - icon_width/2,
                    "y": transformBox.bl.y - icon_width/2
                });
                // team777Common.log("remove_image",remove_image.attr());
                remove_image.data("name", "remove");
                icon_group.push(remove_image);

                if (type == "hide") {
                    icon_group.forEach(function(item) {
                        var name = item.data("name");
                        if (name != "image" && name != "text") {
                            item.hide();
                        }
                    });
                }
                operate_g.add(move_image)
                    .add(path)
                    .add(circle)
                    .add(scale_image)
                    .add(remove_image)
                    .add(rotate_image);

                svgObj.operate_g = operate_g;
                //当前选中的控件
                svgObj.selectGroup = icon_group;
                // icon_group.push($textarea);
                svg_container.on("touchstart", function(e) {
                    e.preventDefault();
                    // hideMouseToolTips();
                    var tagName = e.target.tagName;
                    // team777Common.log("当前点击的元素名称为：" + tagName);
                    if (tagName == "image") {
                        return;
                    }
                    var group = svgObj.selectGroup;
                    if (group) {
                        group.forEach(function(item) {
                            var name = item.data("name");
                            if (name != "image" && name != "text") {
                                item.hide();
                            } else {
                                item.data("prevObjId", null);
                            }
                        });
                        svgObj.selectGroup = null;
                    }
                });
                icon_group.forEach(function(item) {
                    var name = item.data("name");
                    if (!name || name == "circle" || name == "path") {
                        return false;
                    }
                    item.target = target;
                    // if (name == "text") {
                    // }
                    item.on("touchstart", function(e) {
                        var currentObj = this;
                        var name = currentObj.data("name");
                        // team777Common.log("当前名称为：" + name);
                        var selectGroup = svgObj.selectGroup;
                        var tempTarget = currentObj.target;
                        // var prevObjId = "";
                        // var currentObjId = "";
                        // variablePool.prevClickTargetFlag = false;
                        // //若点击的为文字或者素材  设置这次的id
                        // if (name == "text" || name == "image") {
                        //     if (tempTarget) {
                        //         prevObjId = tempTarget.data("prevObjId");
                        //         currentObjId = tempTarget.attr("id");
                        //         tempTarget.data("prevObjId", currentObjId);
                        //     }
                        // }
                        // //如果两次id不为空并且相等则说明可以
                        // if (prevObjId && currentObjId && prevObjId == currentObjId) {
                        //     variablePool.prevClickTargetFlag = true;
                        // }
                        e.preventDefault();
                        bbox = tempTarget.tbox();
                        variablePool.new_pos = null;
                        var o_pos = variablePool.o_pos = variablePool.start_pos = team777Common.getTouchedPosition(e, offset);
                        var id = tempTarget.attr("id");
                        switch (name) {
                            case "image":
                                if (selectGroup) {
                                    selectGroup.each(function(item) {
                                        var name = item.data("name");
                                        if (name != "image" && name != "text") {
                                            item.hide();
                                        }
                                    });
                                }
                                icon_group.forEach(function(item) {
                                    var name = item.data("name");
                                    if (name != "image" && name != "text" && name != "circle") {
                                        item.show();
                                    }
                                });
                                svgObj.selectGroup = icon_group;
                                svgObj.operate_g = operate_g;
                                that.refreshComponent(tempTarget, icon_group);
                                break;
                            case "rotate":
                                circle.show();
                                break;
                            case "remove":
                                var name = tempTarget.data("name");
                                var id = tempTarget.attr("id");
                                var type = tempTarget.data("type");
                                operate_g.remove();
                                tempTarget.remove();
                                break;
                            default:
                                break;
                        }
                        variablePool.mouseStatus = true;
                        var transform = tempTarget.transform();
                        svg_container.on("touchmove", function(e) {
                            e.preventDefault();
                            e.stopPropagation();
                            if (!variablePool.mouseStatus) {
                                return;
                            }
                            var new_pos = variablePool.new_pos = team777Common.getTouchedPosition(e, offset);
                            o_pos = variablePool.o_pos;
                            transform = tempTarget.transform();
                            var ratio=variablePool.viewbox_ratio;
                            ratio=1;
                            var dis_pos = {
                                x: (new_pos.point1.x - o_pos.point1.x)*ratio,
                                y: (new_pos.point1.y - o_pos.point1.y)*ratio
                            };
                            switch (name) {
                                case "image":
                                case "move":
                                    if (team777Common.isDragging(e)) {
                                        var x = dis_pos.x*variablePool.viewbox_ratio + transform.x;
                                        var y = dis_pos.y*variablePool.viewbox_ratio + transform.y;
                                        tempTarget.translate(x, y);
                                    } else if (team777Common.isPinching(e)) {
                                        var oldScaleX = transform.scaleX;
                                        var scaleX = Math.max(0, Math.min(oldScaleX * (team777Common.getZooms(new_pos) / team777Common.getZooms(o_pos)), 10));

                                        tempTarget.scale(scaleX, scaleX);
                                        var center = { x: bbox.cx, y: bbox.cy };
                                        var deg1 = team777Common.getAngles(o_pos);
                                        var deg2 = team777Common.getAngles(new_pos);
                                        var angle = deg2 - deg1;
                                        angle = angle + transform.rotation;
                                        tempTarget.rotate(angle);
                                    }
                                    that.refreshComponent(tempTarget, icon_group);
                                    break;
                                case "scale":
                                    var center = { x: bbox.cx, y: bbox.cy};
                                    o_pos.point2 = center;
                                    new_pos.point2 = center;
                                    var oldScaleX = transform.scaleX;
                                    var scaleX = Math.max(0, Math.min(oldScaleX * (team777Common.getZooms(new_pos) / team777Common.getZooms(o_pos)), 10));
                                    tempTarget.scale(scaleX, scaleX);
                                    that.refreshComponent(tempTarget, icon_group);
                                    // team777Common.log("中心-开始-结束点位置坐标：",center,variablePool.o_pos,variablePool.new_pos)
                                    break;
                                case "rotate":
                                    var center = { x: bbox.cx, y: bbox.cy};
                                    // var ratio=variablePool.viewbox_ratio;
                                    var y0 = (o_pos.point1.y - center.y),
                                        x0 = (o_pos.point1.x - center.x)
                                        y = (new_pos.point1.y - center.y),
                                        x = (new_pos.point1.x - center.x);
                                    var deg = Math.atan2(y, x) - Math.atan2(y0, x0);
                                    var angle = 180 * deg / Math.PI;
                                    angle = angle + transform.rotation;
                                    tempTarget.rotate(angle);
                                    that.refreshComponent(tempTarget, icon_group);
                                    break;
                                default:
                                    break;
                            }
                            variablePool.o_pos = variablePool.new_pos;
                        });
                        svg_container.on("touchend", function(e) {
                            e.preventDefault();
                            var end_pos = variablePool.o_pos;
                            var start_pos = variablePool.start_pos;
                            var dis_pos = {
                                x: end_pos.point1.x - start_pos.point1.x,
                                y: end_pos.point1.y - start_pos.point1.y
                            };
                            // team777Common.log("当前移动的距离为:"+dis_pos.x+"---"+dis_pos.y);
                            variablePool.mouseStatus = false;
                            switch (name) {
                                case "rotate":
                                    circle.hide();
                                    break;
                                case "image":
                                    if (dis_pos.x != 0 || dis_pos.y != 0) {
                                        break;
                                    }
                                    e.preventDefault();
                                    // var type = tempTarget.data("type");
                                    //如果为用户图片则显示操作工具条
                                    // if (type == "uploadImage") {
                                    //     showMouseToolTips(e);
                                    // }
                                    break;
                                default:
                                    break;

                            }
                            svg_container.off("touchmove");
                            svg_container.off("touchend");
                        });
                    });
                });
            }
        }
    });
    // team777Common.log(vueApp);
})();

window.diyPage||(diyPage={
    template:{
        origin_price:1,
        kind:"mobile"
    },
    options: null,
    coupon:0,
    upLoadUrl:null,
    init:function () {
        var me=this;
        me.getElement();
        me.options = {
            pdata: window.location.href.getQueryJson()
        }
        me.DEMO.detail.val(CommonJs.cookie.get('addressContont') || '');
        var cookAddress = CommonJs.cookie.get('addressList');
        if (cookAddress) {
            try {
                cookAddress = JSON.parse(decodeURIComponent(cookAddress));
                addAddress.address = cookAddress;
            } catch (e) {
            }
        }
        me.verification.Me = me;
        addAddress.init();
    },
    getElement:function () {
        var me=this;
        me.DEMO={
            price: $("#price"),
            editMaterialbox: $(".edit-material-box"),
            addOrder: $(".add-order"),
            receiver: $("#receiver"),            // 收件人
            remark: $("#remark"),                // 备注
            mobile: $("#mobile"),                // 手机号码
            detail: $("#detail"),                // 详细地址
            counts: $("#counts"),                // 购买数量
            coupon: $("#coupon")                 // 优惠码
        }
    },
    openAddOrd: function () {
        var me = this;
        me.DEMO.addOrder.addClass("show");
    },
    closeAddOrd: function () {
        var me = this;
        me.DEMO.addOrder.removeClass("show");
    },
    counts: function (type) {
        this.getElement();
        var me = this,
            counts = me.DEMO.counts.val();
        counts = counts ? parseInt(counts) : 1;
        if (type == 'add') {
            counts += 1;
        } else if (type == 'minus') {
            if (counts > 1) {
                counts -= 1;
            }
        } else {
            if (counts <= 1) {
                counts = 1;
            }
        }
        me.DEMO.price.text("￥" + (parseFloat(me.template.origin_price)*parseFloat(counts || 1)-me.coupon).toFixed(2));
        me.DEMO.counts.val(counts)
    },
    getCoupon:function () {
        var me=this,
            couponVal=me.DEMO.coupon.val();
        me.getElement();
        if(couponVal) {
            $.ajax({
                type: "POST",
                url: STATIC_CONFIG.WWWROOT + "/index/index/getCoupon",
                dataType: 'json',
                data: {
                    coupon_code: couponVal
                },
                success: function (result) {
                    if(result.code==200){
                        me.coupon=parseFloat(result.message.coupon||0);
                        me.DEMO.price.text("￥" + (parseFloat(me.template.origin_price)*parseFloat(me.DEMO.counts.val()||1)-me.coupon).toFixed(2));
                    }
                },
                error: function () {
                }
            });
        }else{
            me.coupon=0;
            me.DEMO.price.text("￥" + (parseFloat(me.template.origin_price)*parseFloat(me.DEMO.counts.val()||1)-me.coupon).toFixed(2));
        }
    },
    verification: {
        Me: null,
        phone: function () {
            var me = this,
                errorMsg = '',
                box = me.Me.DEMO.mobile.parents(".text-box");
            if (me.Me.DEMO.mobile.nulls()) {
                errorMsg = '请输入手机号';
            } else if (!me.Me.DEMO.mobile.val().isMobile()) {
                errorMsg = '手机号格式不正确';
            }
            if (errorMsg != '') {
                me.Me.error(box, errorMsg, me.phoneTime);
                return false;
            } else {
                box.removeClass('error');
                return true;
            }
        }
    },
    error: function (t, msg, timeName) {
        var me = this,
            that = $(t),
            box = that.hasClass('text-box') ? that : that.parents(".text-box");
        box.attr('data-hint', msg);
        box.addClass('error');
        clearTimeout(timeName);
        timeName = setTimeout(function () {
            box.removeClass('error');
        }, 1000);
    },
    uploadStaus: true,
    upload: function () {
        var me = this,
            status = true;
        if (!me.verification.phone()) {
            status = false;
        }
        if (me.DEMO.receiver.nulls()) {
            me.error(me.DEMO.receiver, '请填写收件人', me.receiverTime);
            status = false;
        }
        if (me.DEMO.detail.nulls()) {
            me.error(me.DEMO.detail, '请填写详细地址', me.receiverTime);
            status = false;
        }
        if (status && me.uploadStaus) {
            addAddress.getElement();
            me.uploadStaus = false;
            CommonJs.cookie.set('receiver', me.DEMO.receiver.val());
            CommonJs.cookie.set('mobile', me.DEMO.mobile.val());

            CommonJs.cookie.set('addressList', JSON.stringify(addAddress.address));
            CommonJs.cookie.set('addressContont', me.DEMO.detail.val());

            var postData = {
                "user_id": CommonJs.cookie.get('user_id'),
                "counts": me.DEMO.counts.val(),
                "coupon": '',
                "receiver": me.DEMO.receiver.val(),
                "mobile": me.DEMO.mobile.val(),
                "telephone": '',
                "province_id": addAddress.DOEM.province.val(),//"用户所属省ID",
                "province": addAddress.DOEM.province.find("option:selected").text(),//"用户所属省",
                "city_id": addAddress.DOEM.city.val(),//"用户所属城市ID",
                "city": addAddress.DOEM.city.find("option:selected").text(),//"用户所属城市",
                "district_id": addAddress.DOEM.district.val(),//"用户地址所在区县ID",
                "district": addAddress.DOEM.district.find("option:selected").text(),//"用户地址所在区县",
                "detail": me.DEMO.detail.val(),
                "is_default": '0',
                "product_id": me.template.product_id,
                "mask_id": '',
                "chartlet_id": '',
                "remark": '',
                "type": me.options.pdata.type,
                "coupon_code": me.DEMO.coupon.val(),
                "content":me.upLoadUrl,
                "kind":me.template.kind
            }
            $.ajax({
                type: "POST",
                url: STATIC_CONFIG.WWWROOT + "/index/index/commitOrder",
                dataType: 'json',
                data: postData,
                success: function (result) {
                    setTimeout(function () {
                        me.uploadStaus = true;
                    },1000);
                    if (result.code == 200) {
                        if(result.message=='free'){
                            layer.open({
                                content: result.imsg,
                                shadeClose: false,
                                time: 2.5
                            });
                            setTimeout(function () {
                                window.location.href = "//wechat.zfpresent.com/order";
                            },2500);
                        }else {
                            window.location.href = "/pay/?package=" + result.message.package;
                        }
                    } else {
                        layer.open({
                            content: result.imsg,
                            shadeClose: false,
                            time: 2.5
                        });
                    }
                },
                error: function () {
                    me.uploadStaus = true;
                }
            });
        }
    }
});
diyPage.init();
